package com.jason.library.common.adapter

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter

class CommonViewPagerAdapter(fm: FragmentManager?) :
    FragmentPagerAdapter(fm!!, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {

    private var fragments = mutableListOf<Fragment>()
    private var titles = mutableListOf<String>()

    fun addFragment(fragment: Fragment) {
        fragments.add(fragment)
    }

    fun addFragment(fragment: Fragment, title: String) {
        fragments.add(fragment)
        titles.add(title)
    }

    fun addFragments(
        fragments: MutableList<Fragment>,
        titles: MutableList<String>
    ) {
        fragments.addAll(fragments)
        titles.addAll(titles)
    }

    fun setFragments(
        fragments: MutableList<Fragment>,
        titles: MutableList<String>
    ) {
        fragments.clear()
        titles.clear()
        fragments.addAll(fragments)
        titles.addAll(titles)
    }

    fun addTitles(titles: MutableList<String>) {
        titles.addAll(titles)
        notifyDataSetChanged()
    }

    fun clearTitles() {
        titles.clear()
    }

    override fun getItem(i: Int): Fragment {
        return fragments[i]
    }

    override fun getCount(): Int {
        return fragments.size
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return if (titles.isEmpty()) {
            super.getPageTitle(position)
        } else titles[position]
    }
}